package com.itheima.pinda.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pinda.common.utils.PageResponse;
import com.itheima.pinda.common.utils.Result;
import com.itheima.pinda.entity.Member;
import com.itheima.pinda.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * 用户管理模块
 *
 * @author llhuang10
 * @date 2021/10/7 19:53
 */
@Slf4j
@Validated
@RestController
@Api(tags = "用户管理模块")
@RequestMapping("/member")
public class MemberController {

    @Resource
    private MemberService memberService;

    /**
     * 新增用户
     *
     * @param member 用户
     * @return 返回结果
     */
    @PostMapping
    @ApiOperation("新增用户")
    public Result save(@Valid @RequestBody Member member) {
        boolean res = memberService.save(member);
        return res ? Result.ok() : Result.error();
    }

    /**
     * 根据Id查询用户
     *
     * @param id 用户id
     * @return 用户信息
     */
    @GetMapping("/detail/{id}")
    @ApiOperation("根据Id查询用户")
    public Member detail(@NotBlank(message = "用户id不能为空!") @PathVariable("id") String id) {
        return memberService.getById(id);
    }

    /**
     * 分页查询
     *
     * @param page     当前页
     * @param pageSize 每页大小
     * @return 分页返回结果
     */
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public PageResponse<Member> page(Integer page, Integer pageSize) {
        Page<Member> pageResult = memberService.page(new Page<>(page, pageSize), Wrappers.<Member>lambdaQuery());

        return PageResponse.<Member>builder()
                .items(pageResult.getRecords())
                .page(page)
                .pagesize(pageSize)
                .pages(pageResult.getPages())
                .counts(pageResult.getTotal())
                .build();
    }

    /**
     * 修改用户信息
     *
     * @param id     用户Id
     * @param member 用户信息
     * @return 返回结果
     */
    @PutMapping("/{id}")
    @ApiOperation("修改用户信息")
    public Result update(@NotBlank(message = "用户id不能为空!") @PathVariable("id") String id,
                         @Valid @RequestBody Member member) {
        member.setId(id);
        boolean res = memberService.updateById(member);
        return res ? Result.ok() : Result.error();
    }

    /**
     * 删除用户信息
     *
     * @param id 用户Id
     * @return 返回结果
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除用户信息")
    public Result del(@NotBlank(message = "用户id不能为空!") @PathVariable("id") String id) {
        boolean res = memberService.removeById(id);
        return res ? Result.ok() : Result.error();
    }

}
